package qinggui.mlz.console.controller.star;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import qinggui.mlz.console.domain.PageVO;
import qinggui.mlz.module.category.entity.Category;
import qinggui.mlz.console.domain.star.StarListVO;
import qinggui.mlz.console.domain.star.StarVO;
import qinggui.mlz.module.category.service.CategoryService;
import qinggui.mlz.module.star.entity.Star;
import qinggui.mlz.module.star.entity.dto.StarDTO;
import qinggui.mlz.module.star.service.StarService;
import qinggui.mlz.module.utils.BaseUtils;
import qinggui.mlz.module.utils.Response;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class StarController {
    @Autowired
    private StarService starService;
    @Autowired
    private CategoryService categoryService;


    /**
     * 获取所有球星
     *
     * @param page 页码
     * @return PageVO<Star>
     */
    @RequestMapping("/star/list")
    public Response getAllList(@RequestParam Integer page) {
        // 参数校验
        if (page == null || page <= 0) {
            return new Response<>(4004, "页码参数不合法");
        }
        Integer pageSize = 10;
        List<StarDTO> allList;
        try {
            allList = starService.getAllList(page, pageSize);
        } catch (Exception e) {
            log.error("获取球星列表失败：", e);
            return new Response<>(4004);
        }
        List<StarListVO> starListVOS = new ArrayList<>();
        Integer total = starService.getAllCount();
        allList.forEach(star -> {
            starListVOS.add(new StarListVO().setId(star.getId())
                    .setImages(star.getImages())
                    .setCategoryName(star.getCategoryName())
                    .setName(star.getName())
                    .setAge(star.getAge())
                    .setGender(star.getGender())
                    .setWorkPlace(star.getWorkPlace())
                    .setScore(star.getScore())
                    .setPay(star.getPay())
                    .setAssist(star.getAssist())
                    .setBackboard(star.getBackboard())
                    .setCreateTime(star.getCreateTime())
                    .setUpdateTime(star.getUpdateTime())
            );
        });
        PageVO<StarListVO> starListVOPageVO = new PageVO<StarListVO>().setTotal(total).setList(starListVOS).setPageSize(pageSize);
        return new Response<>(1001, starListVOPageVO);
    }

    /**
     * 获取球星详情
     *
     * @param id 球星id
     * @return StarVO
     */
    @RequestMapping("/star/details")
    public Response getAllListApp(@RequestParam Long id) {
        if (id == null) {
            return new Response<>(4004, "球星ID不能为空");
        }
        Star star;
        try {
            star = starService.getById(id);
        } catch (Exception e) {
            log.error("获取球星详情失败：", e);
            return new Response(4004, "获取球星详情失败");
        }
        if (star == null) {
            return new Response<>(4004, "球星不存在");
        }
        // 处理图片列表
        List<String> imagesList = new ArrayList<>();
        if (star.getImages() != null && !star.getImages().isEmpty()) {
            String[] images = star.getImages().split("\\$");
            imagesList = new ArrayList<>(Arrays.asList(images));
        }
        // 根据类目id，查询对应的类目名称
        Category category = categoryService.getById(star.getCategoryId());
        if (category == null) {
            return new Response<>(4004, "类目不存在");
        }
        String categoryName = category.getCategoryName();
        // 获取秒级时间戳
        Integer createTime = star.getCreateTime();
        Integer updateTime = star.getUpdateTime();
        StarVO starVO = new StarVO().setId(star.getId())
                .setImages(imagesList)
                .setCategoryName(categoryName)
                .setName(star.getName())
                .setAge(star.getAge())
                .setGender(star.getGender())
                .setWorkPlace(star.getWorkPlace())
                .setScore(star.getScore())
                .setPay(star.getPay())
                .setAssist(star.getAssist())
                .setBackboard(star.getBackboard())
                .setCreateTime(BaseUtils.timeStamp2DateGMT(createTime, "yyyy-MM-dd HH:mm:ss"))
                .setUpdateTime(BaseUtils.timeStamp2DateGMT(updateTime, "yyyy-MM-dd HH:mm:ss"));
        return new Response(1001, starVO);
    }

    /**
     * 新增球星
     *
     * @param images    多张图片地址
     * @param name      球星名字
     * @param age       球星年龄
     * @param gender    性别
     * @param workPlace 效力于
     * @param score     得分
     * @param pay       薪资
     * @param assist    助攻
     * @param backboard 篮板
     * @return String
     */
    @RequestMapping("/star/insert")
    public Response<String> add(@RequestParam String images, @RequestParam Long categoryId, @RequestParam String name, @RequestParam Integer age, @RequestParam Integer gender,
                                @RequestParam String workPlace, @RequestParam Float score, @RequestParam Float pay, @RequestParam Float assist, @RequestParam Float backboard, @RequestParam(required = false) String description, @RequestParam(required = false) String tags) {
        try {
            starService.edit(null, images.trim(), categoryId, name.trim(), age, gender, workPlace.trim(), score, pay, assist, backboard, description, tags);
        } catch (Exception e) {
            log.error("添加球星失败：", e);
            return new Response<>(4004, "添加失败");
        }
        return new Response<>(1001, "添加成功");
    }

    /**
     * 删除球星
     *
     * @param id 球星id
     * @return String
     */
    @RequestMapping("/star/delete")
    public Response<String> delete(@RequestParam Long id) {
        try {
            starService.delete(id);
        } catch (Exception e) {
            log.error("删除球星失败：", e);
            return new Response<>(4004, "删除失败");
        }
        return new Response<>(1001, "删除成功");
    }

    /**
     * 更新球星
     *
     * @param id        球星id
     * @param images    多张图片地址
     * @param name      球星名字
     * @param age       球星年龄
     * @param gender    性别
     * @param workPlace 效力于
     * @param score     得分
     * @param pay       薪资
     * @param assist    助攻
     * @param backboard 篮板
     * @return String
     */
    @RequestMapping("/star/update")
    public Response<String> update(@RequestParam Long id, @RequestParam String images, @RequestParam Long categoryId, @RequestParam String name, @RequestParam Integer age,
                                   @RequestParam Integer gender, @RequestParam String workPlace, @RequestParam Float score, @RequestParam Float pay,
                                   @RequestParam Float assist, @RequestParam Float backboard, @RequestParam(required = false) String description, @RequestParam(required = false) String tags) {
        try {
            starService.edit(id, images, categoryId, name.trim(), age, gender, workPlace.trim(), score, pay, assist, backboard, description, tags);
        } catch (Exception e) {
            log.error("更新球星失败：", e);
            return new Response<>(4004, "更新失败");
        }
        return new Response<>(1001, "更新成功");
    }
}

